/**
 * Copyright (c) 2021-2028, iron.guo 郭成杰 (jiedreams@sina.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.beluga.core.strategy.impl;

import com.beluga.core.model.wechat.BaseWxPayResult;
import com.beluga.core.model.PayModel;
import com.beluga.core.model.wechat.WxBPayUnifiedOrder;
import com.beluga.core.model.wechat.WxBPayUnifiedResult;
import com.beluga.core.pay.BPayModel;
import com.beluga.core.pay.SignType;
import com.beluga.core.pay.TradeType;
import com.beluga.core.props.WxPayProperties;
import com.beluga.core.strategy.BPayStrategy;
import com.beluga.core.util.WxPayTools;
import com.beluga.core.wechat.WechatPayApi;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author iron.guo
 * @Date 2022/5/2
 * @Description
 */
@Service
@AllArgsConstructor
public class WxPayServiceImpl implements BPayStrategy {

    private WxPayProperties wxPayProperties;

    /**
     * 获取微信支付令牌
     *
     * @param payModel
     * @return
     */
    @Override
    public Map<String,String> payToken(PayModel payModel) {
        WxBPayUnifiedOrder unifiedOrder=new WxBPayUnifiedOrder();
        unifiedOrder.setNonceStr(WxPayTools.generateStr());
        unifiedOrder.setOpenid(payModel.getOpenid());
        unifiedOrder.setBody(payModel.getDescription());
        unifiedOrder.setTotalFee(unifiedOrder.yuanToFen(payModel.getAmount()));
        unifiedOrder.setOutTradeNo(payModel.getOutTradeNo());
        unifiedOrder.setSpbillCreateIp(payModel.getSpbillCreateIp());
        unifiedOrder.setNotifyUrl(payModel.getCallback());
        unifiedOrder.setSignType(SignType.HMACSHA256.getType());
        unifiedOrder.setTradeType(TradeType.JSAPI.getTradeType());
        unifiedOrder.checkAndSign(wxPayProperties);
        String result = WechatPayApi.pushOrder(payModel.getIsSandbox(), unifiedOrder);
        WxBPayUnifiedResult wxBPayUnifiedResult = BaseWxPayResult.fromXML(result, WxBPayUnifiedResult.class);
        Map<String, String> wxPayMap = BPayModel.getWxPayMap(TradeType.JSAPI, wxBPayUnifiedResult.getPrepayId(),SignType.HMACSHA256, wxPayProperties);
        return wxPayMap;
    }


}
